import React from 'react';
import { Modal, message } from 'antd';
import type { ModalProps } from 'antd';
import DynamicForm from '../components/DynamicForm';
import type { FormItem, FormConfig } from '../components/DynamicForm';

/**
 * 用户表单弹窗组件
 * 用于新增或编辑用户信息
 */
interface UserFormModalProps extends Partial<ModalProps> {
  visible: boolean;
  onCancel: () => void;
  onSuccess?: (data: Record<string, unknown>) => void;
  initialValues?: Record<string, unknown>;
  mode?: 'add' | 'edit';
}

const UserFormModal: React.FC<UserFormModalProps> = ({ 
  visible,
  onCancel,
  onSuccess,
  mode = 'add',
  ...otherProps
}) => {
  // 模拟数据：省份和城市的级联选择数据
  const cascaderOptions = [
    {
      value: 'beijing',
      label: '北京',
      children: [
        { value: 'chaoyang', label: '朝阳区' },
        { value: 'haidian', label: '海淀区' },
        { value: 'dongcheng', label: '东城区' },
      ],
    },
    {
      value: 'shanghai',
      label: '上海',
      children: [
        { value: 'pudong', label: '浦东新区' },
        { value: 'xuhui', label: '徐汇区' },
        { value: 'jingan', label: '静安区' },
      ],
    },
    {
      value: 'guangdong',
      label: '广东',
      children: [
        { value: 'guangzhou', label: '广州' },
        { value: 'shenzhen', label: '深圳' },
        { value: 'dongguan', label: '东莞' },
      ],
    },
  ];

  // 模拟数据：用户角色选项
  const roleOptions = [
    { label: '管理员', value: 'admin' },
    { label: '普通用户', value: 'user' },
    { label: '访客', value: 'guest' },
  ];

  // 模拟数据：用户兴趣选项
  const interestOptions = [
    { label: '阅读', value: 'reading' },
    { label: '旅游', value: 'traveling' },
    { label: '运动', value: 'sports' },
    { label: '音乐', value: 'music' },
    { label: '编程', value: 'programming' },
  ];

  // 模拟数据：性别选项
  const genderOptions = [
    { label: '男', value: 'male' },
    { label: '女', value: 'female' },
    { label: '其他', value: 'other' },
  ];

  // 表单项配置
  const formItems: FormItem[] = [
    {
      label: '用户名',
      name: 'username',
      type: 'text',
      props: {
        placeholder: '请输入用户名',
        maxLength: 20,
      },
      rules: [
        { required: true, message: '请输入用户名' },
        { min: 3, message: '用户名长度至少为3个字符' },
      ],
    },
    {
      label: '密码',
      name: 'password',
      type: 'text',
      props: {
        placeholder: '请输入密码',
        type: 'password',
      },
      rules: mode === 'add' 
        ? [
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码长度至少为6个字符' },
          ]
        : [],
    },
    {
      label: '姓名',
      name: 'name',
      type: 'text',
      props: {
        placeholder: '请输入姓名',
        maxLength: 10,
      },
      rules: [{ required: true, message: '请输入姓名' }],
    },
    {
      label: '性别',
      name: 'gender',
      type: 'radio',
      props: {
        options: genderOptions,
      },
      rules: [{ required: true, message: '请选择性别' }],
    },
    {
      label: '出生日期',
      name: 'birthdate',
      type: 'date',
      props: {
        placeholder: '请选择出生日期',
        format: 'YYYY-MM-DD',
      },
      rules: [{ required: true, message: '请选择出生日期' }],
    },
    {
      label: '电子邮箱',
      name: 'email',
      type: 'text',
      props: {
        placeholder: '请输入电子邮箱',
        type: 'email',
      },
      rules: [
        { required: true, message: '请输入电子邮箱' },
        { type: 'email', message: '请输入有效的电子邮箱地址' },
      ],
    },
    {
      label: '手机号码',
      name: 'phone',
      type: 'text',
      props: {
        placeholder: '请输入手机号码',
        maxLength: 11,
      },
      rules: [
        { required: true, message: '请输入手机号码' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' },
      ],
    },
    {
      label: '所在地',
      name: 'location',
      type: 'cascader',
      props: {
        options: cascaderOptions,
        placeholder: '请选择所在地区',
        fieldNames: { value: 'value', label: 'label', children: 'children' },
      },
      rules: [{ required: true, message: '请选择所在地区' }],
    },
    {
      label: '用户角色',
      name: 'role',
      type: 'select',
      props: {
        options: roleOptions,
        placeholder: '请选择用户角色',
        allowClear: false,
      },
      rules: [{ required: true, message: '请选择用户角色' }],
    },
    {
      label: '兴趣爱好',
      name: 'interests',
      type: 'checkbox',
      props: {
        options: interestOptions,
        mode: 'multiple'
      },
      rules: [{ required: true, message: '请选择至少一个兴趣爱好', type: 'array', min: 1 }],
    },
    {
      label: '个人简介',
      name: 'bio',
      type: 'text',
      props: {
        placeholder: '请输入个人简介',
        rows: 4,
        maxLength: 200,
        showCount: true,
      },
      rules: [
        { required: true, message: '请输入个人简介' },
        { min: 10, message: '个人简介长度至少为10个字符' },
      ],
    },
  ];

  // 处理表单提交
  const handleSubmit = (values: Record<string, unknown>) => {
    try {
      // 格式化日期字段
      const formattedValues = {
        ...values,
        birthdate: values.birthdate ? String(values.birthdate) : null,
      };
      
      // 模拟API请求延迟
      setTimeout(() => {
        message.success(mode === 'add' ? '用户新增成功' : '用户编辑成功');
        
        // 调用成功回调
        if (onSuccess) {
          onSuccess(formattedValues);
        }
        
        // 关闭弹窗
        onCancel();
      }, 500);
    } catch (error) {
      message.error('提交失败，请重试');
      console.error('Submit error:', error);
    }
  };

  // 处理表单重置
  const handleReset = () => {
    // message.info('表单已重置');
    onCancel();
  };

  // 表单配置
  const formConfig: FormConfig = {
    items: formItems,
    onSubmit: handleSubmit,
    onReset: handleReset,
    layout: 'horizontal',
    labelWidth: 200,
    labelCol: { span: 4 }, // 自定义标签列宽度
    wrapperCol: { span: 24 }, // 自定义输入框列宽度
    itemsPerRow: 1,
    collapsed: false,
    defaultShowCount: formItems.length, // 显示所有字段
    submitText: mode === 'add' ? '新增' : '保存',
    resetText: '取消',
    actionColSpan: 24, // 操作按钮列宽度，默认为6
  };

  return (
    <Modal
      title={mode === 'add' ? '新增用户' : '编辑用户'}
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={940}
      destroyOnClose
      {...otherProps}
    >
      <DynamicForm {...formConfig} />
    </Modal>
  );
};

export default UserFormModal;